package com.su.lightthings.utils

import android.content.Context
import android.media.AudioManager
import android.media.MediaPlayer
import android.media.RingtoneManager
import com.su.lightthings.base.BaseApplication
import java.io.IOException
import java.util.Timer
import java.util.TimerTask


object RingUtil {

    private var timer: Timer? = null
    private var timerTask: TimerTask? = null

    fun control(event: Int) {
        when (event) {
            0 -> start()
            1 -> stop()
        }
    }

    private fun stop() {
        timer?.cancel()
        timerTask?.cancel()
    }


    private fun start() {
        if (timer != null) {
            timer?.cancel()
            timer = null
        }
        if (timerTask != null) {
            timerTask?.cancel()
            timerTask = null
        }
        timer = Timer()
        timerTask = object : TimerTask() {
            override fun run() {
                ring()
            }
        }
        timer?.schedule(timerTask, 0, 2000)
    }

    private fun ring() {
        val mp = MediaPlayer()
        try {
            mp.setDataSource(
                BaseApplication.instance,
                RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            )
            mp.prepare()
            mp.start()
            mp.setVolume(1.0f, 1.0f);
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun maxVolume(type: Int) {
        val am = BaseApplication.instance.getSystemService(Context.AUDIO_SERVICE) as AudioManager
        val direction = when (type) {
            1 -> AudioManager.ADJUST_LOWER
            2 -> AudioManager.ADJUST_RAISE
            else -> AudioManager.ADJUST_SAME
        }
        am.setStreamVolume(AudioManager.STREAM_NOTIFICATION, direction, 0)
    }
}